//
//  TIMConversionViewController.m
//  Demo_sdk
//
//  Created by Deli Xia on 2018/6/28.
//  Copyright © 2018年 Deli Xia. All rights reserved.
//

#import "TIMConversionViewController.h"
#import "TIMDemoMacro.h"
#import "TIMChatListCell.h"
#import "TIMChatMessageViewController.h"

#import "TIMStorageModel.h"
#import "TIMStorageManager.h"
#import "TIMApi.h"
#import "TIMCommon.h"

static NSString *CellReuseID = @"ChatListCell";

@interface TIMConversionViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableview;
@property (strong, nonatomic) NSArray *dataSource;

@property (nonatomic, strong) NSMutableDictionary *inviteWaitDic;

@end

@implementation TIMConversionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataSource = [[TIMStorageManager sharedStorageManager] getAllConversationsInfo];
    self.title = @"会话";
    self.inviteWaitDic = [NSMutableDictionary dictionary];
    [self.view addSubview:self.tableview];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateList) name:TIM_FINISH_LOGIN_SYNC_SERVER_BROADCAST object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateGroup:) name:TIM_OPERATION_GROUP_BROADCAST object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateGroup:) name:TIM_FROM_SERVER_MESSAGE_BROADCAST object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receicveFriend:) name:TIM_OPERATE_FRIEND_ACTION_BROADCAST object:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.dataSource =  [[TIMStorageManager sharedStorageManager] getAllConversationsInfo];
    [self.tableview reloadData];
}

- (void)updateList {
    dispatch_async(dispatch_get_main_queue(), ^{
        self.dataSource =  [[TIMStorageManager sharedStorageManager] getAllConversationsInfo];
        [self.tableview reloadData];
    });
}

#pragma mark - Notification

- (void)receicveFriend:(NSNotification *)notification {
    NSDictionary *userInfo = notification.userInfo;
    switch ([userInfo[@"TIMMessageFriendOperation"] integerValue]) {
        case TIMMsgOperation_OperationFriAdd:
            NSLog(@"好友操作： TIMMsgOperation_OperationFriAdd");
        case TIMMsgOperation_OperationFriConfirm:
            NSLog(@"好友操作： TIMMsgOperation_OperationFriConfirm");
            break;
        default:
            break;
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        self.dataSource = [[TIMStorageManager sharedStorageManager] getAllConversationsInfo];
        [self.tableview reloadData];
    });
}

- (void)updateGroup:(NSNotification *)notification {
    NSDictionary *userInfo = notification.userInfo;
    TIMMessage *message = [userInfo valueForKey:@"message"];
    switch ([[userInfo valueForKey:@"operateGroupType"] integerValue]) {
        case TIMOperateGroupTypeCreateGroup:
            NSLog(@"操作群组：TIMOperateGroupTypeCreateGroup");
            break;
        case TIMOperateGroupTypeOfferGroup:
              NSLog(@"操作群组：TIMOperateGroupTypeOfferGroup");
            break;
        case TIMOperateGroupTypeRemoveGroup:
              NSLog(@"操作群组：TIMOperateGroupTypeRemoveGroup");
            break;
        case TIMOperateGroupTypeExitGroup:
              NSLog(@"操作群组：TIMOperateGroupTypeExitGroup");
            break;
        case TIMOperateGroupTypeModifyGroupName:
              NSLog(@"操作群组：TIMOperateGroupTypeModifyGroupName");
            break;
        case TIMOperateGroupTypeDismissGroup:
              NSLog(@"操作群组：TIMOperateGroupTypeDismissGroup");
            break;
        case TIMOperateGroupTypeModifyMemoGroup:
              NSLog(@"操作群组：TIMOperateGroupTypeModifyMemoGroup");
            break;
        case TIMOperateGroupTypeStopTalkGroup:
              NSLog(@"操作群组：TIMOperateGroupTypeStopTalkGroup");
            break;
        case TIMOperateGroupTypeOpenTalkGroup:
              NSLog(@"操作群组：TIMOperateGroupTypeOpenTalkGroup");
            break;
        case TIMOperateGroupTypeTransferOwner:
              NSLog(@"操作群组：TIMOperateGroupTypeTransferOwner");
            break;
        case TIMOperateGroupTypeAddAdminGroup:
              NSLog(@"操作群组：TIMOperateGroupTypeAddAdminGroup");
            break;
        case TIMOperateGroupTypeDeleteAdminGroup:
              NSLog(@"操作群组：TIMOperateGroupTypeDeleteAdminGroup");
            break;
        case TIMOperateGroupTypeGroupOfferStop:
              NSLog(@"操作群组：TIMOperateGroupTypeGroupOfferStop");
            break;
        case TIMOperateGroupTypeGroupOfferOpen:
              NSLog(@"操作群组：TIMOperateGroupTypeGroupOfferOpen");
            break;
        case TIMOperateGroupTypeGrpOfferAuditCommit:
            [self setupCustomMessage:message];
            NSLog(@"操作群组：TIMOperateGroupTypeGrpOfferAuditCommit");
            return;
            break;
        default:
            break;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        self.dataSource = [[TIMStorageManager sharedStorageManager] getAllConversationsInfo];
        [self.tableview reloadData];
    });
}

- (void)setupCustomMessage:(TIMMessage *)message {
    if (self.inviteWaitDic) {
        NSMutableArray *messageArray = [self.inviteWaitDic objectForKey:message.groupID];
        if (messageArray == nil) {
            messageArray = [NSMutableArray array];
            [messageArray addObject:message];
        } else {
            for (NSString *groupID in [self.inviteWaitDic allKeys]) {
                if (groupID == message.groupID) {
                    [messageArray addObject:message];
                }
            }
        }

        [self.inviteWaitDic setObject:messageArray forKey:message.groupID];
    }

    NSString *messageText = message.text;
    NSString *content = [NSString stringWithFormat:@"[%d条进群申请]%@",[[self.inviteWaitDic objectForKey:message.groupID] count],messageText];
    [[TIMStorageManager sharedStorageManager] updateConversionContentByGroupId:message.groupID content:content isShow:YES];

    dispatch_async(dispatch_get_main_queue(), ^{
        self.dataSource = [[TIMStorageManager sharedStorageManager] getAllConversationsInfo];
        [self.tableview reloadData];
    });
}

#pragma mark - TableView Delegate or Datasource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TIMChatListCell *cell = [tableView dequeueReusableCellWithIdentifier:CellReuseID];
    TIMConversationInfo *conversation = self.dataSource[indexPath.row];
    [cell setConversation:conversation];
    cell.lineView.hidden = indexPath.row == self.dataSource.count - 1 ? YES : NO;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    TIMConversationInfo *conversation = self.dataSource[indexPath.row];
    TIMChatMessageViewController *vc = [TIMChatMessageViewController new];
    if (conversation.convType == TIMConversationTypePersonal) {
        TIMUserInfo *userInfo = [[TIMStorageManager sharedStorageManager] getFriendByFriendID:conversation.partnerID];
        [[TIMStorageManager sharedStorageManager] readConversionByPartnerId:userInfo.userID];
        vc.messagePartner = userInfo;
    } else if (conversation.convType == TIMConversationTypeGroup) {
//        TIMGroupInfo *groupInfo = [[TIMStorageManager sharedStorageManager] getGroupInfoByGroupID:conversation.partnerID];
        
//        for (TIMMessage *message in self.inviteWaitArray) {
//            if (message.groupID == groupInfo.groupID) {
//
//            }
//        }
        
        // 清空最后一条信息文本
//        [[TIMStorageManager sharedStorageManager] updateConversionContentByGroupId:groupInfo.groupID content:nil isShow:NO];
//        [TIMApi queryGroupUserFromServerWithGroupId:conversation.partnerID version:0 completion:^(NSError *error) {
//           
//        }];
       
        TIMGroupInfo *groupInfo = [[TIMStorageManager sharedStorageManager] getGroupInfoByGroupID:conversation.partnerID];
        [TIMApi queryGroupUserFromServerWithGroupId:groupInfo.groupID version:0 completion:nil];
        [[TIMStorageManager sharedStorageManager] readConversionByPartnerId:groupInfo.groupID];
        vc.messagePartner = groupInfo;
        
//        [[TIMStorageManager sharedStorageManager] readConversionByPartnerId:groupInfo.groupID];
//        vc.messagePartner = groupInfo;
    }
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - Getter

- (UITableView *)tableview {
    if (!_tableview) {
        _tableview = [[UITableView alloc] initWithFrame:Frame(0, 10, self.view.frame.size.width, self.view.frame.size.height - 64 - 10) style:UITableViewStylePlain];
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.showsHorizontalScrollIndicator = NO;
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.rowHeight = 64;
        _tableview.backgroundColor = DefaultBackGroundColor;
        [_tableview registerClass:NSClassFromString(@"TIMChatListCell") forCellReuseIdentifier:CellReuseID];
    }
    return _tableview;
}

@end
